<template>
	<view>
		<v-leaflet ref="gdleafletwx"></v-leaflet>
		<!-- <map id="map" class="map" :latitude="centerLat" :longitude="centerLon" style="width: 100%; height: 100%; position: absolute"></map> -->
		<view class="tabTop">
			<scroll-view scroll-x="true" :scroll-left="scrollLeft" :scroll-with-animation="true">
				<view class="box" :style="{ width: totalWidth + 'px' }">
					<view class="tabTopItem" v-for="(item, index) in tabList" :key="index" :class="{ ac: tabTopCurrent == index }" @click="tabTopChange(item, index)">
						<image :src="item.iconUrl" class="tips"></image>
						<text class="name">{{ item.name }}</text>
					</view>
				</view>
			</scroll-view>
		</view>
		<view class="detail-box" v-if="showDetail">
			<view class="detail-view" @click="toDetails">
				<image class="detail-img" :src="detailInfo.pics[0].objKey" />
				<view class="detail-content">
					<view class="detail-title" style="">{{ detailInfo.locationName }}</view>
					<view class="detail-address">{{ detailInfo.address }}</view>
				</view>
			</view>
			<view class="btn-box">
				<button class="cu-btn round" @click="toDetails">查看详情</button>
				<button class="cu-btn round" @click="navigate">导航</button>
			</view>
		</view>

		<view class="route-detail-box" v-if="showRouteDetail">
			<view class="address-view">
				<image class="route-img" :src="detailInfo.objKeys[0]" />
				<view class="address-content">
					<view class="address-title">{{ detailInfo.locationName }}</view>
					<view class="address-desc">{{ detailInfo.address }}</view>
				</view>
				<view class="address-btn-box">
					<view class="nav-btn" @click="navigate">
						<image src="https://nownc178.cq4oss.ctyunxs.cn/index/icon_navigator.png"></image>
					</view>
					<button class="detail-btn" @click="toDetails">详情</button>
				</view>
			</view>
			<view class="route-view">
				<view class="route-title">{{ selectedRoute.routeName }}</view>
				<view class="route-top-box">
					<text class="route-info">{{ scheduleList.length }}个日程丨{{ travelList.length }}个行程</text>
					<button class="cu-btn bg-white" @click="toRouteDetail">
						查看详情
						<uni-icons type="arrow-right" color="#137576" size="20"></uni-icons>
					</button>
				</view>
				<!-- <van-tabs :change="onChange">
					<van-tab :title="item.scheduleName" v-for="(item,index) in scheduleList" :key="item.id" ></van-tab>
				</van-tabs> -->
				<uni-segmented-control :current="currentTab" :values="scheduleNameList" @clickItem="onChange" styleType="text" activeColor="#137576"></uni-segmented-control>
				<view class="schedule" style="margin-top: 30rpx; padding: 0 30rpx">
					<stepBar :stepList="travelList" @clickStep="clickStep"></stepBar>
				</view>
			</view>
		</view>

		<uni-popup ref="routePopup" type="bottom">
			<view class="route-list" v-for="(item, index) in routeList" :key="item.id">
				<view @click="selectRoute(item)">
					<view>{{ item.routeName }}</view>
				</view>
			</view>
		</uni-popup>
		<line-select :show="line_show"></line-select>
		<left-popup></left-popup>
	</view>
</template>

<script>
import { appLocPage, getTypeList, getTravelRouteList, getTravelRouteDetail } from '@/api/index.js';
// import popup from '@/components/popup/popup.vue';
// import LineSelect from '@/components/lineSelect/popup.vue';
import leftPopup from '@/components/leftPopup/leftPopup.vue';
const plugin = requirePlugin('zhgeo-plugin');
import { mapGetters } from 'vuex';
import stepBar from '@/components/stepBar/stepBar.vue';

export default {
	components: {
		// popup,
		// LineSelect,
		leftPopup,
		stepBar
	},
	data() {
		return {
			active: 0,
			lctShow: false,
			line_show: false,
			showSecondMenu: false,
			showDetail: false,
			showRouteDetail: false,
			detailInfo: {},
			tabList: [
				{
					name: '游线',
					id: 1,
					level: 1,
					children: null,
					iconUrl: 'https://nownc178.cq4oss.ctyunxs.cn/index/icon_route.png'
				}
			], //默认传到顶部菜单栏的数据
			selectedTab: null,
			selectedTag: null,
			itemWidth: 0, //每个item的宽度
			totalWidth: 10000, //设置一个默认总宽度
			scrollLeft: 0, //滑动距离
			tabTopList: [],
			tabTopCurrent: 0,
			routeList: [],
			selectedRoute: {},
			locationList: [],
			scheduleList: [],
			scheduleNameList: [],
			travelList: [],
			currentTab: 0,
			currentLocation: 0,
			centerLat: 29.157879,
			centerLon: 107.099147,
			defaultZoom: 10
		};
	},
	onLoad() {
		/*
			计算总宽度和每个item的宽度
			item宽度 = 自身宽度 + 8px右边距
			总宽度 = item个数 * 每个item的宽度
		*/
		this.$nextTick(() => {
			let dom = uni.createSelectorQuery().select('.tabTopItem');
			dom.boundingClientRect((data) => {
				let num = this.tabTopList.length;
				this.itemWidth = data.width;
				this.totalWidth = num * this.itemWidth;
			}).exec();
		});
	},
	mounted() {
		this.initMap();
		this.getTypeListData();
		this.getLocationListByType();
	},
	methods: {
		initMap() {
			// const container = this.selectComponent('#gd-leafletwx')
			const container = this.$refs.gdleafletwx;
			let that = this;
			container.initLeafletMap(function (L) {
				wx.leaflet ??= {};
				wx.leaflet.L = L;
				var map = L.map(container, {
					minZoom: 9,
					maxZoom: 15
				});
				wx.leaflet.map = map;
				wx.leaflet.markers = [];
				wx.leaflet.lines = [];
				L.tileLayer('https://nownc178.cq4oss.ctyunxs.cn/map5/{z}/{x}/{y}.jpg', {
					subdomains: '1234',
					noWrap: true
					// bounds: rc.getMaxBounds()
				}).addTo(map);

				map.setView([that.centerLat, that.centerLon], that.defaultZoom).on({
					click: (e) => {
						that.showDetail = false;
						that.showRouteDetail = false;
						// that.deleteMapLayers();
					}
				});
			});
		},
		onChange(e) {
			this.currentTab = e.currentIndex;
			this.currentLocation = 0;
			this.travelList = this.scheduleList[e.currentIndex].travelItineraryDTOS;
			this.detailInfo = this.travelList[this.currentLocation].locationDTO;
			this.detailInfo.objKeys = this.travelList[this.currentLocation].objKeys;
			this.computedLine();
		},
		getTypeListData() {
			let that = this;
			getTypeList({}).then((respond) => {
				const dataArr = respond.data;
				if (dataArr && respond.code === 200) {
					dataArr.map((item) => {
						that.tabList.push(item);
					});
				}
			});
		},
		getLocationListByType(id) {
			let that = this;
			const homePoint = 1;
			let data = {
				current: 0,
				size: 100
			};
			if (id) {
				data.locationTypeId = id;
			} else {
				data.homePoint = 1;
			}
			console.log('para:', data);
			appLocPage(data).then((respond) => {
				const dataArr = respond.data;
				that.addMarkerOnMap(dataArr);
			});
		},
		addMarkerOnMap(dataArr) {
			let that = this;
			this.deleteMapLayers();
			for (var i = 0; i < dataArr.length; i++) {
				const item = dataArr[i];
				if (item) {
					let m = wx.leaflet.L.marker([item.latitude, item.longitude], {
						src: 'https://cdn.bootcdn.net/ajax/libs/leaflet/1.9.4/images/marker-icon-2x.png',
						width: 22,
						height: 25,
						title: item.locationName,
						showFooter: true,
						footerWidth: Number(item.locationName.length * 20),
						footerPosition: 1, // 0：左 1:右 2：上 3：下
						// left_badge: '左', //  为空时不显示
						// right_badge: '右', // 为空时不显示
						showInCenter: true // ture: 图标中心在POI中心 false：图标下边缘中心位于POI中心
					}).addTo(wx.leaflet.map);
					wx.leaflet.map.setView([that.centerLat, that.centerLon]);
					m.on({
						click() {
							that.detailInfo = item;
							that.showDetail = true;
							that.showRouteDetail = false;
						}
					});
					wx.leaflet.markers.push(m);
				}
			}
		},
		getRouteData() {
			let that = this;
			this.routeList = [];
			const data = {
				current: 0,
				size: 100
			};
			uni.showLoading({
				title: '加载中'
			});
			getTravelRouteList(data).then((respond) => {
				uni.hideLoading();
				const dataArr = respond.data.records;
				that.routeList = dataArr;
			});
		},
		moveMarkerToCenter(marker) {},
		deleteMapLayers() {
			if (wx.leaflet.markers.length > 0) {
				for (var i = 0; i < wx.leaflet.markers.length; i++) {
					let m = wx.leaflet.markers[i];
					wx.leaflet.map.removeLayer(m);
				}
				wx.leaflet.markers = [];
			}
			if (wx.leaflet.lines.length > 0) {
				for (var i = 0; i < wx.leaflet.lines.length; i++) {
					let l = wx.leaflet.lines[i];
					wx.leaflet.map.removeLayer(l);
				}
				wx.leaflet.lines = [];
			}
		},
		computedLine() {
			this.deleteMapLayers();
			const dataArr = [];
			this.travelList.map((item) => {
				dataArr.push(item.locationDTO);
			});
			console.log('locationArr:', dataArr);
			this.addMarkerOnMap(dataArr);
			for (var i = 0; i < dataArr.length; i++) {
				const item = dataArr[i];
				const nextItem = dataArr[i + 1];
				if (item && nextItem) {
					this.myAmapFun.getDrivingRoute({
						origin: `${item.longitude},${item.latitude}`,
						destination: `${nextItem.longitude},${nextItem.latitude}`,
						success: function (data) {
							var points = [];
							if (data.paths && data.paths[0] && data.paths[0].steps) {
								var steps = data.paths[0].steps;
								// for (var i = 0; i < steps.length; i++) {
								// 	var poLen = steps[i].polyline.split(';');
								// 	for (var j = 0; j < poLen.length; j++) {
								// 		points.push([parseFloat(poLen[j].split(',')[1]), parseFloat(poLen[j].split(',')[0])]);
								// 	}
								// }
							}
							let l = wx.leaflet.L.polyline(points, { color: '#ff0000', weight: 3 }).addTo(wx.leaflet.map);
							wx.leaflet.lines.push(l);
						},
						fail: function (info) {}
					});
				}
			}
		},
		tagClick(item) {
			this.selectedTag = item;
			this.getLocayionList(item.type);
		},
		tabClick(item) {
			// this.showSecondMenu = item.children ? true : false;
			// this.selectedTab = item;
			// this.selectedTag = null;
			// this.getLocayionList(item.type);
		},
		toDetails() {
			uni.navigateTo({
				url: `/pages/map/mapDetail?id=` + this.detailInfo.id
			});
		},
		toRouteDetail() {
			uni.navigateTo({
				url: `/pages/route/routeDetail?id=` + this.selectedRoute.id
			});
		},
		// 点击tab切换高亮，并进行滑动，（index-1）是为了点击项显示在第二栏的位置
		tabTopChange(item, index) {
			this.tabTopCurrent = index;
			this.scrollLeft = this.itemWidth * (index - 1);
			if (index === 0) {
				this.getRouteData();
				this.$refs.routePopup.open('top');
			} else {
				this.getLocationListByType(item.id);
			}
			this.showDetail = false;
			this.showRouteDetail = false;
		},
		selectRoute(item) {
			this.$refs.routePopup.close();
			this.getRouteDetailData(item.id);
		},
		getRouteDetailData(id) {
			let that = this;
			this.scheduleList = [];
			this.scheduleNameList = [];
			this.travelList = [];
			getTravelRouteDetail(id).then((res) => {
				console.log('游线详情数据：', res);
				if (res.data && res.code === 200) {
					that.selectedRoute = res.data;
					that.scheduleList = res.data.travelScheduleDTOS;
					that.scheduleList.map((item) => {
						that.scheduleNameList.push(item.scheduleName);
					});
					that.travelList = res.data.travelScheduleDTOS[that.currentTab].travelItineraryDTOS;
					that.detailInfo = that.travelList[that.currentLocation].locationDTO;
					that.detailInfo.objKeys = that.travelList[that.currentLocation].objKeys;
					that.showRouteDetail = true;
					that.computedLine();
				}
				wx.leaflet.map.setView([that.detailInfo.latitude, that.detailInfo.longitude], that.defaultZoom);
			});
		},
		clickStep(e) {
			console.log(e);
			if (e.locationDTO) {
				this.detailInfo = e.locationDTO;
				this.detailInfo.objKeys = e.objKeys;
				this.centerLat = this.detailInfo.latitude;
				this.centerLon = this.detailInfo.longitude;
				wx.leaflet.map.setView([this.detailInfo.latitude, this.detailInfo.longitude], this.defaultZoom);
			}
		},
		navigate() {
			uni.openLocation({
				latitude: this.detailInfo.latitude,
				longitude: this.detailInfo.longitude,
				name: this.detailInfo.locationName,
				address: this.detailInfo.address,
				success: function () {
					console.log('success');
				}
			});
		},
	},
	computed: {
		// ...mapGetters(['getLocationList'])
	}
};
</script>

<style lang="scss" scoped>
page {
	height: 100%;
	position: relative;
}

.content {
	width: 100%;
	height: 100%;
}

.menu-view {
	width: 100%;
	height: 80px;
	// color: white;
	background-color: white;
	box-shadow: 0rpx 5rpx 5rpx 0rpx rgba(88, 88, 88, 0.35);
	// z-index: 2;
}

.second-menu-view {
	width: 100%;
	height: 50px;
	background-color: white;
	padding: 10px;
	position: absolute;
	top: 50px;
	// z-index: 3;
	.tag-view {
		padding: 5px 15px;
		background-color: #eee;
		border-radius: 20px;
		margin-right: 10px;
		&.active {
			background-color: #cce6ff;
			border: 1px solid #0081ff;
			color: #0081ff;
		}
	}
}

.detail-box {
	position: absolute;
	left: 20px;
	right: 20px;
	bottom: 20px;
	padding: 10px 20px;
	background-color: white;
	border-radius: 10px;
}

.detail-view {
	display: flex;
}

.detail-img {
	width: 125rpx;
	height: 125rpx;
	border-radius: 20rpx;
	flex-shrink: 0;
}

.detail-content {
	margin-left: 15px;
}

.detail-title {
	font-size: 32rpx;
	font-weight: bold;
	margin-bottom: 10rpx;
}

.detail-address {
	font-size: 24rpx;
	font-weight: bold;
}

.btn-box {
	margin-top: 20rpx;
	display: flex;
	justify-content: space-around;
	.cu-btn {
		width: 250rpx;
		height: 50rpx;
		font-weight: bold;
		border: 1px solid #606060;
		background-color: #fff;
	}
}

.route-list {
	background-color: white;
	padding: 10px;
	height: 50px;
}

.route-detail-box {
	position: fixed;
	left: 0px;
	right: 0px;
	bottom: 0px;
}

.address-view {
	padding: 20rpx;
	margin: 12rpx 38rpx;
	display: flex;
	align-items: center;
	background: url('https://nownc178.cq4oss.ctyunxs.cn/index/bg_address_view.png');
	background-size: 100% 100%;
	.route-img {
		flex-shrink: 0;
		width: 125rpx;
		height: 125rpx;
		border-radius: 20rpx;
	}
	.address-content {
		margin: 0 20rpx;
		.address-title {
			color: #ffc600;
			font-size: 44rpx;
			font-family: 'FZCSK--GBK1-0';
		}
		.address-desc {
			color: #1b7576;
			font-size: 18rpx;
		}
	}
	.address-btn-box {
		flex-shrink: 0;
		text-align: center;
		.nav-btn {
			image {
				width: 40rpx;
				height: 40rpx;
			}
		}
		.detail-btn {
			background-color: #1b7576;
			color: #fff;
			border-radius: 4px;
			margin-top: 15rpx;
			font-size: 24rpx;
			line-height: 2;
		}
	}
}

.route-view {
	padding: 30rpx;
	background-color: #fff;
	border-top-left-radius: 40rpx;
	border-top-right-radius: 40rpx;
	.route-top-box {
		display: flex;
		justify-content: space-between;
	}
	.route-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #137576;
		margin-bottom: 20rpx;
	}
}

::v-deep .leaflet-bar {
	display: none;
}

.tabTop {
	position: relative;
	z-index: 1;
	background: #ffffff;
	box-shadow: 5px 0 5px 0 #585858;
	padding: 0 15rpx;
	/* 隐藏滚动条样式 */
	::-webkit-scrollbar {
		width: 0;
		height: 0;
	}
	.box {
		display: flex;
		align-items: center;
		.tabTopItem {
			text-align: center;
			width: 120rpx;
			height: 120rpx;
			font-size: 24rpx;
			font-weight: bold;
			color: #333;
			flex-shrink: 0;
			.tips {
				width: 60rpx;
				height: 60rpx;
				display: block;
				margin: 10rpx auto 6rpx auto;
			}
		}
		.ac {
			font-size: 24rpx;
			color: #009b4c;
			.name {
				position: relative;
				&::after {
					content: '';
					display: block;
					position: absolute;
					bottom: -2rpx;
					left: 2rpx;
					width: calc(100% - 4rpx);
					height: 2rpx;
					background: #009944;
				}
			}
		}
	}
}

/deep/ .component--leafletwx-marker-footer {
	border: 2px solid #fff !important;
	background-color: #009b4c !important;
	border-radius: 8rpx !important;
	color: #fff !important;
	height: 50rpx !important;
}
/deep/ .component--leafletwx-marker-footer-triangle-top {
	display: none;
}
</style>
